import React, { PureComponent, Fragment } from "react";
import { Icon, Menu } from "antd";
import moment from "moment";
import { revFileIcon, formatBytes, jCookie } from "@/utils/smallTool";
import { fileNameConfig } from "@/utils/fieldConfig";
import styles from "./Floder.less";

let count = 0;
const jcookie = jCookie();

class Floder extends PureComponent {
  state = {
    curFileInfo: {},
    showMenu: "",
    fileType: "file",
    showType: jcookie.getCookie("finder") || "list",
    sort: { col: "name", arrow: false },
    menuPositon: {
      top: 0,
      left: 0
    },
    selectedItem: null
  };

  constructor(props) {
    super(props);
    window.onkeypress = this.keyPress;
  }

  componentDidMount() {
    this.setState({ sort: this.props.sort });
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.list !== nextProps.list) {
      this.setState({ selectedItem: null });
    }
  }

  fileClick = (info, event) => {
    const { onFileClick } = this.props;
    count += 1;
    this.fileSelect(info, event);
    setTimeout(() => {
      if (count === 2) {
        onFileClick(info);
      }
      count = 0;
    }, 300);
  };

  fileSelect = (info, event) => {
    event.stopPropagation();
    this.setState({ selectedItem: info });
  };

  rightClick = (event, type, info) => {
    event.persist();
    event.preventDefault();
    event.stopPropagation();
    const { clientX, clientY } = event;
    this.setState({
      curFileInfo: info,
      showMenu: type,
      fileType: info ? info.type : "",
      menuPositon: {
        top: clientY,
        left: clientX
      }
    });
  };

  keyPress = event => {
    const { onKeypress } = this.props;
    if (event.keyCode === 32 || event.keyCode === 13) {
      if (this.state.selectedItem) onKeypress(this.state.selectedItem);
    }
  };

  handleHideMenu = () => {
    this.setState({ showMenu: "", curFileInfo: {} });
  };

  cancleSelect = () => {
    this.setState({ selectedItem: null });
  };

  handleMenuClick = (value, menuCofig) => {
    const { curFileInfo } = this.state;
    value.domEvent.stopPropagation();
    menuCofig.click(curFileInfo, value);
    this.handleHideMenu();
  };

  switchShowType = (event, type) => {
    this.setState({ showType: type });
    jcookie.setCookie("finder", type, 10000);
  };

  backToUp = () => {
    const { onBackToUp } = this.props;
    onBackToUp();
  };

  sortList = event => {
    const { onSortList } = this.props;
    const { sort } = this.state;
    const col = event.target.getAttribute("col");
    const arrow =
      sort.col === col
        ? !sort.arrow
        : event.target.getAttribute("arrow") === "true";
    onSortList({ col, arrow });
    event.target.setAttribute("arrow", arrow ? "true" : "false");
    this.setState({ sort: { col, arrow } });
  };

  render() {
    const { list, path } = this.props;
    const { rightClick } = this;
    const { showMenu, menuPositon, fileType, showType } = this.state;
    const renderMenu = menuConfig => {
      let $config = this.props[menuConfig];

      if (menuConfig === "rightMenu") {
        $config = this.props.rightMenu.filter(item => item.type === fileType)[0]
          .list;
      }
      if ($config) {
        const MenuList = $config.map(item => (
          <Menu.Item
            onClick={event => {
              this.handleMenuClick(event, item);
            }}
            key={item.key}
          >
            {item.name}
          </Menu.Item>
        ));
        return (
          <Menu style={menuPositon} className={styles.menu}>
            {MenuList}
          </Menu>
        );
      }
      return <></>;
    };

    const renderFileItem = () => {
      const fileList = list.map(item => {
        const { name, type, info } = item;

        return (
          <Fragment key={name}>
            <div
              className={`${showType ? styles[showType] : styles.grid} ${
                styles.fileItem
              } ${
                this.state.selectedItem &&
                item.name === this.state.selectedItem.name
                  ? styles.active
                  : ""
              } ${
                this.state.curFileInfo &&
                item.name === this.state.curFileInfo.name
                  ? styles.rightActive
                  : ""
              }`}
              onContextMenu={event => {
                rightClick(event, "rightMenu", item);
              }}
              onClick={event => {
                this.fileClick(item, event);
              }}
              title={`文件名：${name}
类型：${fileNameConfig[type]}
${
  info
    ? `大小：${formatBytes(info.size)}
创建时间：${moment(info.birthtime).format("YYYY-MM-DD HH:mm:ss")}
修改时间：${moment(info.mtime).format("YYYY-MM-DD HH:mm:ss")} `
    : ""
}`}
            >
              {type !== "img" ? (
                <div className={styles.iconBox}>
                  <Icon type={revFileIcon(type, name)} theme="filled" />
                </div>
              ) : (
                ""
              )}

              {type === "img" ? (
                <div className={styles.imageBox}>
                  <img src={`${path}/${name}`} alt="" />
                </div>
              ) : (
                ""
              )}
              <div className={styles.nameBox}>{name}</div>
            </div>
          </Fragment>
        );
      });
      return fileList;
    };
    const renderListItem = () => {
      const fileList = list.map(item => {
        const { name, type, info } = item;

        return (
          <Fragment key={name}>
            <div
              className={`${showType ? styles[showType] : styles.grid} ${
                styles.fileItem
              } ${
                this.state.selectedItem &&
                item.name === this.state.selectedItem.name
                  ? styles.active
                  : ""
              } ${
                this.state.curFileInfo &&
                item.name === this.state.curFileInfo.name
                  ? styles.rightActive
                  : ""
              }`}
              onContextMenu={event => {
                rightClick(event, "rightMenu", item);
              }}
              onClick={event => {
                this.fileClick(item, event);
              }}
            >
              <div className={`${styles.fileds} ${styles.flexMax}`}>
                {type !== "img" ? (
                  <span className={styles.iconBox}>
                    <Icon type={revFileIcon(type, name)} theme="filled" />
                  </span>
                ) : (
                  <span className={styles.imageBox}>
                    <img src={`${path}/${name}`} alt="" />
                  </span>
                )}
                <span className={styles.nameBox}>{name}</span>
              </div>
              <div className={styles.fileds}>
                <span>
                  {info
                    ? moment(info.mtime).format("YYYY-MM-DD HH:mm:ss")
                    : "--"}
                </span>
              </div>
              <div className={styles.fileds}>
                <span>{info ? formatBytes(info.size) : "--"}</span>
              </div>
              <div className={styles.fileds}>
                <span>{fileNameConfig[type]}</span>
              </div>
            </div>
          </Fragment>
        );
      });
      return fileList;
    };

    return (
      <div
        className={`${styles.folderbox} clearfix`}
        onContextMenu={event => {
          rightClick(event, "rightEmptyMenu");
        }}
        onClick={event => {
          event.preventDefault();
          this.handleHideMenu();
          this.cancleSelect();
        }}
      >
        <div className={styles.toolBox}>
          <div className={styles.left}>
            <Icon
              type="appstore"
              className={showType === "grid" ? "active" : ""}
              onClick={event => {
                this.switchShowType(event, "grid");
              }}
            ></Icon>
            <Icon
              type="profile"
              className={showType === "grid" ? "" : "active"}
              onClick={event => {
                this.switchShowType(event, "list");
              }}
            ></Icon>
          </div>
          <div className={`${styles.left} ${styles.marginLeft}`}>
            <Icon
              type="rollback"
              onClick={event => {
                this.backToUp(event);
              }}
            ></Icon>
            <span>{path.replace(/\//g, ">").substr(1)}</span>
          </div>
          <div className={styles.right}>
            <Icon type="menu"></Icon>
          </div>
        </div>
        {showType === "list" ? (
          <div className={styles.listHead}>
            <div
              className={styles.fileds}
              col="name"
              arrow="false"
              onClick={event => {
                this.sortList(event);
              }}
            >
              <span>名称</span>
              {this.state.sort.col === "name" ? (
                <Icon type={this.state.sort.arrow ? "up" : "down"} />
              ) : (
                ""
              )}
            </div>
            <div
              className={styles.fileds}
              col="date"
              arrow="false"
              onClick={event => {
                this.sortList(event);
              }}
            >
              <span>修改日期</span>
              {this.state.sort.col === "date" ? (
                <Icon type={this.state.sort.arrow ? "up" : "down"} />
              ) : (
                ""
              )}
            </div>
            <div
              className={styles.fileds}
              col="size"
              arrow="false"
              onClick={event => {
                this.sortList(event);
              }}
            >
              <span>大小</span>
              {this.state.sort.col === "size" ? (
                <Icon type={this.state.sort.arrow ? "up" : "down"} />
              ) : (
                ""
              )}
            </div>
            <div
              className={styles.fileds}
              col="type"
              arrow="false"
              onClick={event => {
                this.sortList(event);
              }}
            >
              <span>种类</span>
              {this.state.sort.col === "type" ? (
                <Icon type={this.state.sort.arrow ? "up" : "down"} />
              ) : (
                ""
              )}
            </div>
          </div>
        ) : (
          ""
        )}

        {showType === "list" ? renderListItem() : renderFileItem()}
        {showMenu === "rightEmptyMenu" ? renderMenu("rightEmptyMenu") : ""}
        {showMenu === "rightMenu" ? renderMenu("rightMenu") : ""}
      </div>
    );
  }
}
export default Floder;
